<template>
  <section class='f-register' :style="{'height': currentHeight + 'px'}">
    <van-sticky>
      <van-nav-bar class="f-nav-bar" title="实名信息">
        <template #left>
          <van-icon name="arrow-left" size="18" @click="pageBack" />
        </template>
      </van-nav-bar>
    </van-sticky>

    <div class="f-cell">
      <p style="color: #848484">店铺类型</p>
      <van-radio-group v-model="form.auditStatus" direction="horizontal">
        <van-radio :name="1" icon-size="16px">个人用户</van-radio>
        <van-radio :name="2" icon-size="16px" class="f-ml-20">企业用户</van-radio>
      </van-radio-group>
    </div>

    <van-form class="f-mt-14" @submit="onSubmit" input-align="right" error-message-align="right">
      <van-cell-group>
        <van-field v-model="form.idCardName" name="idCardName" label="联系人姓名" placeholder="请输入联系人姓名"
          :rules="[{ required: true, message: '请填写联系人姓名' }]" />

        <van-field v-model="form.idCardNum" name="idCardNum" label="联系人证件号" type="tel" placeholder="请输入联系人证件号" maxlength="18"
          :rules="[{ required: true, message: '请填写联系人证件号' },
          { pattern: /^[1-9]\d{5}(18|19|20)\d{2}((0[1-9])|(1[0-2]))(([0-2][1-9])|10|20|30|31)\d{3}[0-9Xx]$/, message: '请填写正确的证件号码'}]" />
      </van-cell-group>

      <van-field v-if="form.auditStatus == 1" class="f-mt-14" name="idcardUrl" label="文件上传"
        :rules="[{ required: false, message: '请上传联系人证件照片' }]">
        <template #label>
          <p>联系人证件照片</p>
          <p class="f-mt-05 f-fs-12 ">(身份证人像面)</p>
        </template>
        <template #input>
          <van-uploader v-model="form.idcardUrl" :after-read="afterRead" :max-count="1" :preview-size="['167px', '104px']">
            <img class="f-img1" src="@/assets/imgs/jhh_datum_pic01.png" alt="">
          </van-uploader>
        </template>
      </van-field>

      <van-field v-if="form.auditStatus == 2" class="f-mt-14" v-model="form.companyName" name="企业名称" label="企业名称"
        placeholder="请输入企业名称" :rules="[{ required: true, message: '请填写企业名称' }]" />
      <van-field v-if="form.auditStatus == 2" name="licenseUrl" label="文件上传" :rules="[{ required: true, message: '请上传上传营业执照' }]">
        <template #label>
          <p>上传营业执照</p>
        </template>
        <template #input>
          <van-uploader v-model="form.licenseUrl" :after-read="afterRead1" :max-count="1" :preview-size="['167px', '104px']">
            <img class="f-img1" src="@/assets/imgs/jhh_btn_bl.png" alt="">
          </van-uploader>
        </template>
      </van-field>

      <div class="f-tips">
        <p>温馨提示：</p>
        <p>1.手机上已安装支付宝App；</p>
        <p>2.支付宝登录账号的实名信息务必与上方联系人姓名、证件号一致，否则将影响您的实名认证结果。</p>
      </div>

      <div class="f-submit-btn">
        <van-button round block type="primary" native-type="submit">支付宝实名认证</van-button>
      </div>
    </van-form>

    <liulanqiopen ref="liulanqiopenRef" />

    <qrcode-pop ref="qrcodePopRef" />

  </section>
</template>
<script>
import { ref, reactive, toRefs, onMounted, watch, onBeforeUnmount, computed } from 'vue';
import { useRouter, useRoute } from 'vue-router'
import { useStore } from "vuex";
import api from './api'
import { getStore, successDeal, getUrlParam } from '@/utils/utils';
import JsBridge from '@/utils/JsBridge.js'
import liulanqiopen from '@/components/liulanqiopen.vue'
import qrcodePop from '@/components/qrcodePop'

export default {
  components: {
    liulanqiopen,
    qrcodePop,
  },
  setup(props, context) {
    const store = useStore()

    const router = useRouter()
    const route = useRoute();

    const liulanqiopenRef = ref(null)
    const qrcodePopRef = ref(null)

    const state = reactive({
      form: {
        "auditStatus": 1,
        "companyName": "",
        "contactsName": "",
        "idCardName": "",
        "idCardNum": "",
        "shopUserPhone": "",
        "source": 1
      },
      idcardUrl: '',
      licenseUrl: '',

      timer: null,
      currentHeight: "",
      isApp: computed(() => {
        return store.state.isApp
      }),
      isWeixin: computed(() => {
        var ua = navigator.userAgent.toLowerCase();
        var isWeixin = ua.indexOf('micromessenger') != -1;
        if (isWeixin) {
          return true;
        } else {
          return false;
        }
      }),
    })

    onMounted(() => {
      state.currentHeight = window.innerHeight
      state.form.shopUserPhone = route.query.shopUserPhone
    })

    const afterRead = (params) => {
      params.status = 'uploading';
      params.message = '上传中...';

      const formData = new FormData();
      formData.append("file", params.file) // 这里填入你的file文件对象

      api.uploadImg(formData).then(res => {
        params.status = 'done';
        state.idcardUrl = res.data.ossUrl
      }).catch(err => {
        params.status = 'failed';
        params.message = '上传失败';
      })
    };

    const afterRead1 = (params) => {
      params.status = 'uploading';
      params.message = '上传中...';

      const formData = new FormData();
      formData.append("file", params.file) // 这里填入你的file文件对象

      api.uploadImg(formData).then(res => {
        params.status = 'done';
        state.licenseUrl = res.data.ossUrl
      }).catch(err => {
        params.status = 'failed';
        params.message = '上传失败';
      })
    };

    const onSubmit = (values) => {
      let json = JSON.parse(JSON.stringify(state.form))
      json.contactsName = json.idCardName
      json.idcardUrl = state.idcardUrl
      json.licenseUrl = state.licenseUrl
      if (state.isApp) {
        api.livingCheck(json).then(res => {
          if (res.code == '200') {
            alipayAuth(res.data)
          }
        })
      } else {
        api.livingCheckH5(json).then(res => {
          if (res.code == '200') {
            if (state.isWeixin) {
              const murl = `alipays://platformapi/startapp?appId=20000067&url=${encodeURIComponent(res.data.qrUrl)}`
              qrcodePopRef.value.dialogShow(murl)
              return
            }
            alipayAuth(res.data)
          }
        })
      }
    };

    const livingResult = (orderNo) => {
      let json = {
        orderNo
      }
      api.livingResult(json).then(res => {
        if (res.data?.signState == 1) return
        clearInterval(state.timer)
        successDeal(res.msg)
        if (res.data?.signState == 4) {
          router.go(-1)
        }
      }).catch(err => {
        clearInterval(state.timer)
        console.log(err)
      })
    }

    // 支付宝实名认证
    const alipayAuth = (params) => {
      if (state.isApp) {
        JsBridge.callHandler('alipayAuth', params.infoStr, (res) => {
          if (res) {
            let data = JSON.parse(res)
            successDeal(data.msg)
            let url = data.result.result
            let json = {
              "appId": getUrlParam('app_id', url),
              "authCode": getUrlParam('auth_code', url),
              "certVerifyId": params.verifyId,
              "scope": getUrlParam('scope', url),
              "source": "111"
            }
            api.signNotify(json).then(response => {
              pageBack()
              successDeal('支付宝实名认证成功，请登录！')
            })
          }
        })
      } else {
        const murl = `alipays://platformapi/startapp?appId=20000067&url=${encodeURIComponent(params.qrUrl)}`
        setTimeout(() => {
          window.open(murl, '_blank')
        }, 100);
        clearInterval(state.timer)
        state.timer = setInterval(() => {
          livingResult(params.orderNo)
        }, 2000)
      }
    }

    const pageBack = () => {
      router.go(-1)
    };

    onBeforeUnmount(() => {
      clearInterval(state.timer)
    })

    return {
      ...toRefs(state),
      liulanqiopenRef,
      qrcodePopRef,
      afterRead,
      afterRead1,
      onSubmit,
      pageBack,
    }
  }
}
</script>
<style lang='scss' scoped>
.f-register {
  background: #f3f3f3;
  .f-cell {
    width: 375px;
    height: 53px;
    background: #ffffff;
    display: flex;
    align-items: center;
    justify-content: space-between;
    font-size: 14px;
    padding: 20px 15px;
  }
  .f-mt-14 {
    margin-top: 14px;
  }
  .f-tips {
    padding: 31px 14px;
    font-size: 10px;
    color: #ff2b2b;
    p {
      //   padding-bottom: 5px;
      line-height: 20px;
    }
  }
  .f-submit-btn {
    margin-top: 30px;
    margin-bottom: 30px;
    padding: 0 62px;
  }
  .f-img1 {
    width: 167px;
    height: 104px;
  }
  .f-nav-bar {
    padding-top: 27px;
    background: #000000;
  }
}
</style>